import { Card, Form, Select } from "antd";
import { useEffect } from "react";
// import "./index.less";
import { setCategory1, setCategory2, setCategory3 } from "@/app/category";

import { reqCategory1, reqCategory2, reqCategory3 } from "@/api/hopelist/index";
import { useDispatch, useSelector } from "react-redux";
import { useForm } from "antd/lib/form/Form";

export default function Category() {
  // 加载store中的数据
  const category = useSelector((state: any) => state.category);

  // 获取派发对象
  const dispath = useDispatch();

  // 获取一级分类 赋值
  const getCategory1 = async () => {
    const res = await reqCategory1();
    // console.log(res)
    // 处理数据
    const arr = res.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
      };
    });

    // 赋值到store
    dispath(setCategory1(arr));
  };

  // 获取二级数据 赋值
  const getCategory2 = async (id: number) => {
    // 清除二三级
    dispath(setCategory2([]));
    dispath(setCategory3([]));

    form.setFieldsValue({
      value2: "",
      value3: "",
    });

    const res = await reqCategory2(id);

    const arr = res.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
      };
    });

    dispath(setCategory2(arr));
  };

  // 获取三级 赋值
  const getCategory3 = async (id: number) => {
    // 清除三级
    dispath(setCategory3([]));
    form.setFieldsValue({
      value3: "",
    });

    const res = await reqCategory3(id);
    const arr = res.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
      };
    });

    dispath(setCategory3(arr));
  };

  useEffect(() => {
    // 获取一级
    getCategory1();
  }, []);

  const [form] = useForm();

  const { Option } = Select;

  return (
    <>
    <Card>
      <Form form={form}>
        <Form.Item label="一级分类">
          <Select onSelect={getCategory2}>
            {category.category1.map((item: any) => {
              return <Option value={item.value}>{item.label}</Option>;
            })}
          </Select>
        </Form.Item>
        <Form.Item label="二级分类" name="value2">
          <Select onSelect={getCategory3}>
            {category.category2.map((item: any) => {
              return <Option value={item.value}>{item.label}</Option>;
            })}
          </Select>
        </Form.Item>
        <Form.Item label="三级分类" name="value3">
          <Select>
            {category.category3.map((item: any) => {
              return <Option value={item.value}>{item.label}</Option>;
            })}
          </Select>
        </Form.Item>
      </Form>
      </Card>

      {/* <span>一级分类</span>
      <Select
        placeholder="请选择"
        onChange={getCategory2}
        options={category.category1}
      />

      <span>二级分类</span>
      <Select
        placeholder="请选择"
        onChange={getCategory3}
        options={category.category2}
      />
      <span>三级分类</span>
      <Select placeholder="请选择" options={category.category3} /> */}
    </>
  );
}
